# -*- coding: utf-8 -*-
# !/usr/bin/env python

from fastapi import APIRouter
from fastapi import File, UploadFile
from starlette.responses import HTMLResponse
from starlette.requests import Request
from starlette.templating import Jinja2Templates
from starlette.responses import FileResponse
from starlette.staticfiles import StaticFiles
from typing import List
import os

router = APIRouter()
templates = Jinja2Templates(directory="templates")
router.mount("/static", StaticFiles(directory="./static"), name="static")


@router.get("/", summary='查看图片', description='根据图片ID查看图片')
def index(request: Request):
    return templates.TemplateResponse('/files/upload.html', {'request': request})


@router.get("/download/{file_name}", summary='下载图片', description='根据图片名称下载图片')
def main(request: Request, file_name: str):
    return FileResponse(path=f'./static/data/{file_name}', filename=file_name)


@router.post("/upload/")
async def upload_files(files: UploadFile = File(...)):
    contents = await files.read()
    with open("./static/data/" + files.filename, "wb") as f:
        f.write(contents)
    return {"filename": files.filename}


@router.post("/uploads/")
async def upload_files(files: List[UploadFile] = File(...)):
    for file in files:
        contents = await file.read()
        with open("./static/data/" + file.filename, "wb") as f:
            f.write(contents)
    return {"filename": [file.filename for file in files]}
